//
//  JCWADGuideVC.swift
//  HengYouCai
//
//  Created by wll on 2017/11/8.
//  Copyright © 2017年 lwj. All rights reserved.
//  广告页--代码

import UIKit

class JCWADGuideVC: BaseViewController {

    ///是否是从引导页进入默认No
    var isFromGuide: Bool = false
    ///广告图
    let adImageV = UIImageView(frame: CGRect(x: 0, y: 0, width: JCWSCREENW, height: JCWSCREENH))
    ///跳过按钮
    let jumpIntoBtn = UIButton(type: .custom)
    
    var codeTimer: DispatchSourceTimer?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.barTintColor = UIColor.white
        self.navigationController?.navigationBar.isHidden = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.clear
//        self.getAdGuideImageDataFromNet()
        self.showAddImageV()
    }

    ///获取数据  因为需要控制是否显示  所以请求放在程序入口
    private func getAdGuideImageDataFromNet() {
        //"adImageLinkUrl"
        //https://hbimg.b0.upaiyun.com/2c9a109be64b2f30eb93b82528a4d1ea2d65ea0624f6c9-eqwsSj_fw658
        //"adShowTime"
        //3
        //"adTitle"
        //广告标题
        //"adIsShow"
        //"adImageUrl"
        //https://hbimg.b0.upaiyun.com/4b97b60056048193354bca47512d8c5a9f1feef041477-Cvh9s9_fw658
        

    }
    
    ///展示广告
    private func showAddImageV() {
        let json = JSON(parseJSON: WLFileManager.readUserData(forKey: kJCWADGuideImageUrl) as? String ?? "")
        
        let imageUrl: String = json["adImageUrl"].stringValue.isEmpty ? "emptyyy":json["adImageUrl"].stringValue
//        self.adImageV.kf.setImage(with: ImageResource(downloadURL: URL(string: imageUrl)!), placeholder: self.isFromGuide ? UIImage(named: "Guide3"):UIImage.wl_getLaunch(), options: nil, progressBlock: nil, completionHandler: nil)
        
        self.adImageV.kf_setImage(with: ImageResource(downloadURL: URL(string: imageUrl)!), placeholder: self.isFromGuide ? UIImage(named: "Guide3"):UIImage.wl_getLaunch(), options: nil, progressBlock: nil, completionHandler: nil)
        self.view.addSubview(self.adImageV)
        self.adImageV.isUserInteractionEnabled = true
        self.adImageV.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(jumpToWeb)))
        //倒计时开启
        self.perform(#selector(countDown), with: nil, afterDelay: 0.2)
    }
    
    ///跳转到网页
    func jumpToWeb() {
        self.codeTimer?.cancel()
        let json = JSON(parseJSON: WLFileManager.readUserData(forKey: kJCWADGuideImageUrl) as? String ?? "")
        if let webVC = BannerWebViewVC(urlStr: json["adImageLinkUrl"].stringValue, title: json["adTitle"].stringValue){
            webVC.delegate = self
            webVC.isFromADGuide = true
            self.navigationController?.pushViewController(webVC, animated: true)
            
        }else{
            self.removeAddImageV()
        }
    }
    
    
    ///移除广告
    private func removeAddImageV() {
        self.codeTimer?.cancel()
        let appDelegate: AppDelegate? = JCWShareApplication.delegate as? AppDelegate
        appDelegate?.setRootVCForKeyWindowanimation(true)
    }

    ///倒计时开启
    @objc private func countDown() {
        let json = JSON(parseJSON: WLFileManager.readUserData(forKey: kJCWADGuideImageUrl) as? String ?? "")
        var timeCount: Int = json["adShowTime"].intValue == 0 ?4 : json["adShowTime"].intValue + 1
        //倒计时按钮
        self.jumpIntoBtn.frame = CGRect(x: JCWSCREENW-82, y: 35, width: 70, height: 27.5)
        self.jumpIntoBtn.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        self.jumpIntoBtn.titleLabel?.font = Font_WL(14)
        self.jumpIntoBtn.layer.cornerRadius = 13.75
//        self.jumpIntoBtn.clipsToBounds = true
        self.jumpIntoBtn.setTitleColor(UIColor.white, for: .normal)
        self.jumpIntoBtn.addTarget(self, action: #selector(jumIntoBtnClick), for: .touchUpInside)
        self.jumpIntoBtn.setTitle("跳过\(timeCount)s", for: .normal)
        self.view.addSubview(self.jumpIntoBtn)
        

        // 定义需要计时的时间
        // 在global线程里创建一个时间源
        let codeTimer = DispatchSource.makeTimerSource(queue:      DispatchQueue.global())
        self.codeTimer = codeTimer
        // 设定这个时间源是每秒循环一次，立即开始
        codeTimer.scheduleRepeating(deadline: .now(), interval: .seconds(1))
        // 设定时间源的触发事件
        weak var weakSelf = self
        codeTimer.setEventHandler(handler: {
            // 每秒计时一次
            timeCount = timeCount - 1
            // 返回主线程处理一些事件，更新UI等等
            DispatchQueue.main.async {
                debugPrint(timeCount)
                weakSelf?.jumpIntoBtn.setTitle("跳过\(timeCount)s", for: .normal)
            }
            // 时间到了取消时间源
            if timeCount <= 0 {
                codeTimer.cancel()
                DispatchQueue.main.async {
                    weakSelf?.removeAddImageV()
                    return
                }
            }
        })
        // 启动时间源
        codeTimer.resume()
    }
    ///跳过
    func jumIntoBtnClick() {
        self.removeAddImageV()
    }
    
}

///交互响应代理
extension JCWADGuideVC: JSInvestDelegate {
    func jsInvest() {
        
    }
}

